package yang.yu.sunny.domain;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.dayatang.domain.AbstractEntity;

import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

/**
 * 订单项目
 * Created by yyang on 16/3/15.
 */
@Entity
@Table(name = "order_items")
public class OrderItem extends AbstractEntity {

    @ManyToOne
    private Order order;

    @ManyToOne
    private Product product;

    private double unitPrice;

    private double quantity;

    private double totalPrice;

    private double discount;

    protected OrderItem() {
    }

    public OrderItem(Product product, double quantity) {
        this(product, quantity, 0);
    }

    public OrderItem(Product product, double quantity, double discount) {
        this.product = product;
        this.quantity = quantity;
        this.unitPrice = product.getCurrentUnitPrice().orElseThrow(PriceNotFoundException::new);
        this.totalPrice = unitPrice * quantity * (1 - discount);
    }

    public Order getOrder() {
        return order;
    }

    public void setOrder(Order order) {
        this.order = order;
    }

    public Product getProduct() {
        return product;
    }

    public double getUnitPrice() {
        return unitPrice;
    }

    public double getQuantity() {
        return quantity;
    }

    public double getTotalPrice() {
        return totalPrice;
    }

    public double getDiscount() {
        return discount;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }

        if (!(o instanceof OrderItem)) {
            return false;
        }

        OrderItem that = (OrderItem) o;

        return new EqualsBuilder()
                .append(this.getProduct(), that.getProduct())
                .append(this.getOrder(), that.getOrder())
                .isEquals();
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder(17, 37)
                .append(getProduct())
                .append(getOrder())
                .toHashCode();
    }
}
